package cn.rkylin.oms.item.controller;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;

import cn.rkylin.core.controller.ApolloController;
import cn.rkylin.oms.common.annotation.SystemControllerLog;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.common.export.IExport;
import cn.rkylin.oms.goods.vo.PrjSkuVO;
import cn.rkylin.oms.item.dao.ItemDAOImpl;
import cn.rkylin.oms.item.service.IEcSkuGroupService;
import cn.rkylin.oms.item.service.IItemService;
import cn.rkylin.oms.item.vo.EcSkuGroupVO;
import cn.rkylin.oms.item.vo.GroupSkuInfo;
import cn.rkylin.oms.item.vo.ItemVO;
import cn.rkylin.oms.item.vo.SkuVO;
import cn.rkylin.oms.order.service.IOrderService;
import cn.rkylin.oms.order.vo.OrderSkuVO;

/**
 * 平台商品控制器
 *
 * @author wangxing
 * @version 1.0
 * @created 16-2月-2017 9:00:00
 */
@Controller
@RequestMapping("/item")
public class ItemController extends ApolloController {
    private static final Log logger = LogFactory.getLog(ItemController.class);
    // 常量定义
    private static final String PAGE_SELECT_STATEMENT = "pageSelectItem"; // 分页语句Statement名称
    private static final String PAGE_SELECT_STATEMENT_SKU = "pageSelectSku"; // 分页语句Statement名称
    private static final String GOTO_ITEM_LIST = "/item/itemList"; // 跳转到店铺列表页

    /**
     * 平台商品服务层
     */
    @Autowired
    private IItemService itemService;

    @Autowired
    private IEcSkuGroupService ecSkuGroupService;

    @Autowired
    public IOrderService orderService;

    /**
     * 构造函数
     */
    public ItemController() {

    }

    @Override
    public void afterPropertiesSet() throws Exception {
        setExportService((IExport) itemService);
    }

    /**
     * 组合商品设置
     *
     * @param goodsId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/getGroupByEcSkuId")
    public Map<String, Object> getGroupByEcSkuId(String ecSkuId) throws Exception {
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();

        // 取得规格
        List<EcSkuGroupVO> list = StringUtils.isBlank(ecSkuId) ? null : ecSkuGroupService.getEcSkuGroupByEcSkuId(ecSkuId);

        returnMap.put("ecSkuGroupList", list);
        returnMap.put(JSON_RESULT, SUCCESS);

        return returnMap;
    }

    /**
     * 跳转到平台商品列表
     */
    @RequestMapping(value = "/gotoItemList")
    public String gotoItemList() {
        return GOTO_ITEM_LIST;
    }

    /**
     * 跳转到平台商品列表
     *
     * @param quickSearch 快速查询条件
     * @param formJson    高级检索条件
     * @return 返回值JSON格式字符串
     * @Param start 第几页
     * @Param length 每页多少行
     */
    @ResponseBody
    @RequestMapping(value = "/itemList")
    public Map<String, Object> getItemList(String quickSearch, @RequestParam(required = false, defaultValue = "0") int start,
                                           @RequestParam(required = false, defaultValue = "10") int length, String formJson) throws Exception {

        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            // 登录与权限检测
            CurrentUser currentUser = logonCheck(returnMap);
            if (currentUser == null) {
                return returnMap;
            }

            // 处理查询条件
            ItemVO param = new ItemVO();

            // 前台快速搜索条件
            if (StringUtils.isNotBlank(quickSearch)) {
                quickSearch = URLDecoder.decode(quickSearch, "UTF-8");
                if (StringUtils.isNotEmpty(quickSearch)) {
                    param.setSearchCondition(quickSearch.trim());
                }
            }

            if (StringUtils.isNotBlank(formJson)) {
                // 高级查询检索条件
                formJson = URLDecoder.decode(formJson, "UTF-8");
                Map<String, String> mapItem = JSONObject.parseObject(formJson, Map.class);

                // ItemVO itemVO = JSONObject.parseObject(formJson,
                // ItemVO.class);
                if (mapItem != null) {
                    if (StringUtils.isNotEmpty(mapItem.get("prjId"))) {
                        param.setPrjId(mapItem.get("prjId"));
                    }
                    if (StringUtils.isNotEmpty(mapItem.get("shopId"))) {
                        param.setShopId(mapItem.get("shopId"));
                    }
                    if (StringUtils.isNotEmpty(mapItem.get("shopType"))) {
                        param.setShopType(mapItem.get("shopType"));
                    }
                    if (StringUtils.isNotEmpty(mapItem.get("approveStatus"))) {
                        param.setApproveStatus(mapItem.get("approveStatus"));
                    }

                    if (StringUtils.isNotEmpty(mapItem.get("ecItemCode"))) {
                        param.setEcItemCode(mapItem.get("ecItemCode"));
                    }
                    if (StringUtils.isNotEmpty(mapItem.get("ecItemName"))) {
                        param.setEcItemName(mapItem.get("ecItemName"));
                    }
                    if (StringUtils.isNotEmpty(mapItem.get("ecSkuCode"))) {
                        param.setEcSkuCode(mapItem.get("ecSkuCode"));
                    }
                    if (StringUtils.isNotEmpty(mapItem.get("ecSkuName"))) {
                        param.setEcSkuName(mapItem.get("ecSkuName"));
                    }
                    if (StringUtils.isNotEmpty(mapItem.get("outerCode"))) {
                        param.setOuterCode(mapItem.get("outerCode"));
                    }
                    if (StringUtils.isNotEmpty(mapItem.get("itemOuterCode"))) {
                        param.setItemOuterCode(mapItem.get("itemOuterCode"));
                    }

                } else {
                    param.setPrjId("00000000000000000000000000000000");
                }
            }

            param.setPrjId(currentUser.getCurrentProject().getPrjId());

            // 处理转义的字段
            Map<String, String> replaceFieldsMap = new HashMap<String, String>();
            replaceFieldsMap.put("status", "approveStatus");

            // 排序语句生成
            String orderStatement = getOrderString(ItemDAOImpl.class.getName(), PAGE_SELECT_STATEMENT, replaceFieldsMap);
            if (StringUtils.isNotEmpty(orderStatement)) {
                param.setOrderBy(orderStatement);
            }

            // 处理分页
            if (length == -1) {
                length = Integer.MAX_VALUE;
            }
            int page = start / length + 1;

            // 获取分页数据
            PageInfo<ItemVO> itemVOList = itemService.findByWhere(page, length, param);

            // 设置返回结果内容
            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(RECORDS_FILTERED, itemVOList.getTotal());
            returnMap.put(RECORDS_TOTAL, itemVOList.getTotal());
            returnMap.put(RETURN_DATA, itemVOList.getList());
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        // 生成返回结果json串，null内容也需要返回
        return returnMap;
    }

    /**
     * 获取平台规格列表
     *
     * @param ecItemId 平台商品ID
     * @return SkuVO的json串
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/skuList")
    public Map<String, Object> getSkuList(String ecItemId) throws Exception {
        Map<String, Object> returnJSON = new HashMap<String, Object>();
        try {

            SkuVO param = new SkuVO();
            if (StringUtils.isNotEmpty(ecItemId)) {
                param.setEcItemId(ecItemId);
            }

            // 排序语句生成
            String orderStatement = getOrderString(ItemDAOImpl.class.getName(), PAGE_SELECT_STATEMENT_SKU, null, "BaseSkuResultMap");
            if (StringUtils.isNotEmpty(orderStatement)) {
                param.setOrderBy(orderStatement);
            }

            List<SkuVO> skuVOList = itemService.findByWhere(param);

            // 列表中最后项，下拉按钮往上翻(如果<4则会让上面弹出的上拉菜单档到table head下面)
            if (skuVOList != null && skuVOList.size() > 4) {
                skuVOList.get(skuVOList.size() - 1).setReversePosition("dropup");
                skuVOList.get(skuVOList.size() - 2).setReversePosition("dropup");
            }
            if (!skuVOList.isEmpty()) {
                returnJSON.put(JSON_RESULT, SUCCESS);
                returnJSON.put(RECORDS_FILTERED, skuVOList.size());
                returnJSON.put(RECORDS_TOTAL, skuVOList.size());
                returnJSON.put(RETURN_DATA, skuVOList);
            } else {
                returnJSON.put(JSON_RESULT, SUCCESS);
                returnJSON.put(RECORDS_FILTERED, 0);
                returnJSON.put(RECORDS_TOTAL, 0);
                returnJSON.put(RETURN_DATA, skuVOList);
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnJSON.put(JSON_RESULT, FAILED);
            returnJSON.put(JSON_MSG, ex.getMessage());
        }
        return returnJSON;
    }

    /**
     * 查询项目sku list
     *
     * @param quickSkuSearch 快速sku查询
     * @return sku list
     */
    @SuppressWarnings("rawtypes")
    @ResponseBody
    @RequestMapping(value = "/getProjectSkuList")
    public List getProjectSkuList(String quickSkuSearch) throws Exception {
        List retList = null;
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        if (currentUser == null || currentUser.getCurrentProject() == null) {
            // 未登录
            retList = new ArrayList<PrjSkuVO>();
        } else {
            Map<String, Object> param = new HashMap<String, Object>();
            quickSkuSearch = URLDecoder.decode(quickSkuSearch, "UTF-8");
            param.put("quickSkuSearch", quickSkuSearch);
            param.put("prjId", currentUser.getCurrentProject().getPrjId());
            retList = itemService.getProjectSkuList(param);
        }
        return retList;
    }

    /**
     * 查询项目sku list
     *
     * @param quickSkuSearch 快速sku查询
     * @return sku list
     */
    @SuppressWarnings("rawtypes")
    @ResponseBody
    @RequestMapping(value = "/getProjectSkuList4SalesPromotion")
    public List getProjectSkuList(String skuCodes, String isGift) throws Exception {
        List retList = null;
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        if (currentUser == null || currentUser.getCurrentProject() == null) {
            // 未登录
            retList = new ArrayList<PrjSkuVO>();
        } else {
            Map<String, Object> param = new HashMap<String, Object>();
            skuCodes = URLDecoder.decode(skuCodes, "UTF-8");
            String[] skuCodeArray = skuCodes.split(",");
            param.put("isGift", isGift);
            param.put("skuCodeArray", skuCodeArray);
            param.put("prjId", currentUser.getCurrentProject().getPrjId());
            retList = itemService.getProjectSkuList4SalesPromotion(param);
        }
        return retList;
    }

    /**
     * 自动关联系统商品
     *
     * @param ecitemid 平台商品Id
     * @return jsonjson串
     * @throws Exception 异常
     */
    @ResponseBody
    @RequestMapping(value = "/autoRelationSysGoods", method = RequestMethod.POST)
    @SystemControllerLog(module = "平台商品", operation = "自动关联系统商品", keyCode = "ecitemid")
    public Map<String, Object> autoRelationSysGoods(String[] ecitemid) throws Exception {
        // 用于返回值的json对象
        Map<String, Object> returnJSON = new HashMap<String, Object>();

        try {
            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            String errMsg = itemService.autoRelationSysGoods(ecitemid, currentUser.getCurrentProject().getPrjId());

            if ("".equals(errMsg)) {
                returnJSON.put(JSON_RESULT, SUCCESS);
                returnJSON.put(RETURN_DATA, errMsg);
            } else {
                returnJSON.put(JSON_RESULT, FAILED);
                returnJSON.put(JSON_MSG, errMsg);
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnJSON.put(JSON_RESULT, FAILED);
            returnJSON.put(JSON_MSG, ex.getMessage());
        }
        returnJSON.put("ecitemid", ecitemid);
        return returnJSON;
    }

    /**
     * batchancelRelCationSysGoods:批量取消关联系统商品
     *
     * @param ecitemid
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/batchancelRelCationSysGoods", method = RequestMethod.POST)
    @SystemControllerLog(module = "平台商品", operation = "批量取消关联系统商品", keyCode = "ecitemid")
    public Map<String, Object> batchancelRelCationSysGoods(String[] ecitemid) throws Exception {
        // 用于返回值的json对象
        Map<String, Object> returnJSON = new HashMap<String, Object>();

        try {
            returnJSON = itemService.batchancelRelCationSysGoods(ecitemid);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnJSON.put(JSON_RESULT, FAILED);
            returnJSON.put(JSON_MSG, ex.getMessage());
        }
        returnJSON.put("ecitemid", ecitemid);
        return returnJSON;
    }

    /**
     * 手动关联系统商品
     *
     * @param ecSkuId 平台规格Id
     * @return jsonjson串
     * @throws Exception 异常
     */
    @ResponseBody
    @RequestMapping(value = "/manualRelationSysGoods", method = RequestMethod.POST)
    @SystemControllerLog(module = "平台商品", operation = "手动关联系统商品", keyCode = "ecSkuId")
    public Map<String, Object> manualRelationSysGoods(String ecSkuId, String prjSkuId) throws Exception {
        // 用于返回值的json对象
        Map<String, Object> returnJSON = new HashMap<String, Object>();

        try {
            itemService.manualRelationSysGoods(ecSkuId, prjSkuId);

            // 如果保存时检索到待审核状态订单明细中存在该平台商品，要提示出”平台商品**的系统商品对应关系已变更，是否更新相关系统订单商品明细？（仅待审核状态订单）“
            OrderSkuVO orderSkuVO = new OrderSkuVO();
            orderSkuVO.setEcSkuId(ecSkuId);
            // List<OrderSkuVO> list = orderService.getOrderSkuList(orderSkuVO);
            List<OrderSkuVO> list = orderService.getOrderSkuWaitVerifyList(orderSkuVO);
            if (list != null && list.size() > 0) {
                returnJSON.put(JSON_RESULT, QUESTION);
                returnJSON.put(JSON_MSG, "该平台商品的系统商品对应关系已变更，是否更新相关系统订单商品明细？");
            } else {
                returnJSON.put(JSON_RESULT, SUCCESS);
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnJSON.put(JSON_RESULT, FAILED);
            returnJSON.put(JSON_MSG, ex.getMessage());
        }
        returnJSON.put("ecSkuId", ecSkuId);
        return returnJSON;
    }

    /**
     * 如果保存时检索到待审核状态订单明细中存在该平台商品，要提示出”平台商品**的系统商品对应关系已变更，是否更新相关系统订单商品明细？（
     * 仅待审核状态订单）“
     *
     * @param ecSkuId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/doUpdateOrder", method = RequestMethod.POST)
    @SystemControllerLog(module = "平台商品", operation = "关联系统商品以后，更新订单项目对应的系统sku", keyCode = "ecSkuId")
    public Map<String, Object> doUpdateOrder(String ecSkuId, String prjSkuId) throws Exception {
        // 用于返回值的json对象
        Map<String, Object> returnJSON = new HashMap<String, Object>();

        try {
            if (StringUtils.isBlank(ecSkuId) || StringUtils.isBlank(prjSkuId)) {
                returnJSON.put(JSON_RESULT, FAILED);
                returnJSON.put(JSON_MSG, "参数错误");
            } else {
                itemService.doUpdateOrder(ecSkuId, prjSkuId);
                returnJSON.put(JSON_RESULT, SUCCESS);
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnJSON.put(JSON_RESULT, FAILED);
            returnJSON.put(JSON_MSG, ex.getMessage());
        }
        returnJSON.put("ecSkuId", ecSkuId);
        return returnJSON;
    }

    /**
     * 取消关联系统商品
     *
     * @param ecSkuId 平台规格Id
     * @return jsonjson串
     * @throws Exception 异常
     */
    @ResponseBody
    @RequestMapping(value = "/cancelRelationSysGoods", method = RequestMethod.POST)
    @SystemControllerLog(module = "平台商品", operation = "取消关联系统商品", keyCode = "ecSkuId")
    public Map<String, Object> cancelRelationSysGoods(String ecSkuId) throws Exception {
        // 用于返回值的json对象
        Map<String, Object> returnJSON = new HashMap<String, Object>();

        try {
            returnJSON = itemService.cancelRelationSysGoods(ecSkuId);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnJSON.put(JSON_RESULT, FAILED);
            returnJSON.put(JSON_MSG, ex.getMessage());
        }
        returnJSON.put("ecSkuId", ecSkuId);
        return returnJSON;
    }

    /**
     * 店铺库存同步
     *
     * @param shopId 网店Id
     * @return 结果MAP
     * @throws Exception 异常
     */
    @ResponseBody
    @RequestMapping(value = "/synchShopStock", method = RequestMethod.POST)
    @SystemControllerLog(module = "平台商品", operation = "店铺库存同步", keyCode = "shopId")
    public Map<String, Object> synchShopStock(String shopId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();

        try {
            String msg = itemService.synchShopStock(shopId);

            if ("".equals(msg)) {
                returnMap.put(JSON_RESULT, SUCCESS);
                returnMap.put(RETURN_DATA, msg);
            } else {
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, msg);
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        returnMap.put("shopId", shopId);
        return returnMap;
    }

    /**
     * 商品库存同步
     *
     * @param ecItemId 平台商品Id列表
     * @return 结果MAP
     * @throws Exception 异常
     */
    @ResponseBody
    @RequestMapping(value = "/synchItemStock", method = RequestMethod.POST)
    @SystemControllerLog(module = "平台商品", operation = "商品库存同步", keyCode = "ecItemId")
    public Map<String, Object> synchItemStock(String[] ecItemId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();

        try {
            String msg = itemService.synchItemStock(ecItemId);

            if ("".equals(msg)) {
                returnMap.put(JSON_RESULT, SUCCESS);
                returnMap.put(RETURN_DATA, msg);
            } else {
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, msg);
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        returnMap.put("ecItemId", ecItemId);
        return returnMap;
    }

    /**
     * SKU库存同步
     *
     * @param ecSkuId 平台规格Id
     * @return 结果MAP
     * @throws Exception 异常
     */
    @ResponseBody
    @RequestMapping(value = "/synchSkuStock", method = RequestMethod.POST)
    @SystemControllerLog(module = "平台商品", operation = "SKU库存同步", keyCode = "ecSkuId")
    public Map<String, Object> synchSkuStock(String ecSkuId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();

        try {
            String msg = itemService.synchSkuStock(ecSkuId);

            if ("".equals(msg)) {
                returnMap.put(JSON_RESULT, SUCCESS);
                returnMap.put(RETURN_DATA, msg);
            } else {
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, msg);
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        returnMap.put("ecSkuId", ecSkuId);
        return returnMap;
    }

    /**
     * 批量修改SKU库存同步标识
     *
     * @param selectedEcItemId 平台商品Id列表
     * @param opFlag           true:允许，false:不允许
     * @return jsonjson串
     * @throws Exception 异常
     */
    @ResponseBody
    @RequestMapping(value = "/batchUpdateAutoStock", method = RequestMethod.POST)
    @SystemControllerLog(module = "平台商品", operation = "批量修改SKU库存同步标识", keyCode = "selectedEcItemId")
    public Map<String, Object> batchUpdateAutoStock(String[] selectedEcItemId, Boolean opFlag) throws Exception {
        // 用于返回值的json对象
        Map<String, Object> returnJSON = new HashMap<String, Object>();

        try {
            if (opFlag) {
                // 允许库存同步
                itemService.batchUpdateAutoStock(selectedEcItemId, "y");
            } else {
                // 不允许库存同步
                itemService.batchUpdateAutoStock(selectedEcItemId, "n");
            }

            returnJSON.put(JSON_RESULT, SUCCESS);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnJSON.put(JSON_RESULT, FAILED);
            returnJSON.put(JSON_MSG, ex.getMessage());
        }
        returnJSON.put("selectedEcItemId", selectedEcItemId);
        return returnJSON;
    }

    /**
     * 修改SKU同步库存标识
     *
     * @param ecSkuId   平台规格Id
     * @param autoStock 同步库存
     * @return 结果Map
     */
    @ResponseBody
    @RequestMapping(value = "/updateAutoStock", method = RequestMethod.POST)
    @SystemControllerLog(module = "平台商品", operation = "修改SKU同步库存标识", keyCode = "ecSkuId")
    public Map<String, Object> updateAutoStock(String ecSkuId, String autoStock) {
        Map<String, Object> returnMap = new HashMap<String, Object>();

        try {
            itemService.updateAutoStock(ecSkuId, autoStock);

            returnMap.put(JSON_RESULT, SUCCESS);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        returnMap.put("ecSkuId", ecSkuId);
        return returnMap;
    }

    /**
     * 批量设置
     *
     * @param listingEcItemId   自动上架(y)平台商品Id
     * @param delistingEcItemId 自动上架(n)平台商品Id
     * @return jsonjson串
     * @throws Exception 异常
     */
    @ResponseBody
    @RequestMapping(value = "/batchSetting", method = RequestMethod.POST)
    @SystemControllerLog(module = "平台商品", operation = "批量设置商品自动上下架状态", keyCode = "selectedEcItemId")
    public Map<String, Object> batchSetting(String[] selectedEcItemId, Boolean opFlag) throws Exception {
        // 用于返回值的json对象
        Map<String, Object> returnJSON = new HashMap<String, Object>();

        try {
            if (opFlag) { // 必选参数
                // 自动上架
                itemService.batchSetting(selectedEcItemId, "y");
            } else {
                // 自动下架
                itemService.batchSetting(selectedEcItemId, "n");
            }

            returnJSON.put(JSON_RESULT, SUCCESS);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnJSON.put(JSON_RESULT, FAILED);
            returnJSON.put(JSON_MSG, ex.getMessage());
        }
        returnJSON.put("selectedEcItemId", selectedEcItemId);
        return returnJSON;
    }

    /**
     * 商品上下架
     *
     * @param ecitemid   平台商品Id
     * @param listingFlg (true:上架,false:下架)
     * @return jsonjson串
     * @throws Exception 异常
     */
    @ResponseBody
    @RequestMapping(value = "/listingItem", method = RequestMethod.POST)
    @SystemControllerLog(module = "平台商品", operation = "商品上下架", keyCode = "ecitemid")
    public Map<String, Object> listingItem(String[] ecitemid, boolean listingFlg) throws Exception {
        // 用于返回值的json对象
        Map<String, Object> returnJSON = new HashMap<String, Object>();

        try {
            String errMsg = itemService.listingItem(ecitemid, listingFlg);

            if ("".equals(errMsg)) {
                returnJSON.put(JSON_RESULT, SUCCESS);
                returnJSON.put(RETURN_DATA, errMsg);
            } else {
                returnJSON.put(JSON_RESULT, FAILED);
                returnJSON.put(JSON_MSG, errMsg);
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnJSON.put(JSON_RESULT, FAILED);
            returnJSON.put(JSON_MSG, ex.getMessage());
        }
        returnJSON.put("ecitemid", ecitemid);
        return returnJSON;
    }

    /**
     * 画面数据处理
     *
     * @param shopId
     * @param shopName
     * @param splitType
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/updateGroupGoods")
    @SystemControllerLog(module = "平台商品", operation = "画面数据处理", keyCode = "ecitemid")
    public Map<String, Object> updateGroupGoods(@RequestBody GroupSkuInfo groupSkuInfo) throws Exception {
        // 用于返回值的json对象
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, String> mapParm = new HashMap<String, String>();

        Map<String, Object> map = itemService.modifyGroupSkuData(groupSkuInfo);
        resultMap.put("success", map.get("isOk"));
        resultMap.put("rowcount", map.get("count"));
        resultMap.put("errormessage", map.get("errorMessage"));
        resultMap.put("ecitemid", groupSkuInfo.getEcItemId());
        return resultMap;
    }

    /**
     * 根据平台商品添加系统商品
     *
     * @param ecItemIds 平台商品Ids
     * @return jsonjson串
     * @throws Exception 异常
     */
    @ResponseBody
    @RequestMapping(value = "/copyPlatformItem2SystemItem", method = RequestMethod.POST)
    @SystemControllerLog(module = "平台商品", operation = "根据平台商品添加系统商品", keyCode = "ecitemid")
    public Map<String, Object> copyPlatformItem2SystemItem(String[] ecItemIds) throws Exception {
        // 用于返回值的json对象
        Map<String, Object> returnJSON = new HashMap<String, Object>();

        try {
            CurrentUser curUser = WebContextFactory.getWebContext().getCurrentUser();
            String entId = curUser.getCurrentProject().getEntId();
            String entName = curUser.getCurrentProject().getEntName();
            returnJSON = itemService.copyPlatformItem2SystemItem(ecItemIds, entId, entName);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnJSON.put(JSON_RESULT, FAILED);
            returnJSON.put(JSON_MSG, ex.getMessage());
        }
        returnJSON.put("ecitemid", ecItemIds);
        return returnJSON;
    }

    /**
     * 获取平台商品库存数
     * @param itemVO
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getPlatformStockCount", method = RequestMethod.POST)
    public Map<String, Object> getPlatformStockCount(@RequestBody ItemVO itemVO) {
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            returnMap = itemService.getPlatformStockCount(itemVO);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put("success", "false");
            returnMap.put("msg", ex.getMessage());
        }
        return returnMap;
    }
}